package com.youlai.boot.mongo;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.InsertManyResult;
import com.mongodb.client.result.InsertOneResult;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;

import java.util.List;

@Slf4j
public class MongoStaticService {

    /**
     * 获取连接
     * */
    public static MongoDatabase getCollection(String dataBaseName) {
        String uri = "mongodb://user:Admin827@1.92.74.42:7210/" + dataBaseName + "?authSource=admin";
        try (MongoClient mongoClient = MongoClients.create(uri)) {
            MongoDatabase database = mongoClient.getDatabase(dataBaseName);
            log.info("Connected to MongoDB");
            return database;
//            database.getCollection("wordList").insertOne();
        }
    }
    /**
     * 创建数据库-collection
     * */
    public static void createCollection(String dataBaseName, String collectionName) {
        getCollection(dataBaseName).createCollection(collectionName);
    }

    /**
     * 获取连接信息
     * */
    public static void getInfo(String dataBaseName, String collectionName) {
        MongoCollection<Document> collection = getCollection(dataBaseName).getCollection(collectionName);
        long countDocuments = collection.countDocuments();
        log.info("查询的集合{}-数据条数为:{}", collectionName, countDocuments);
    }

    /**
     * 插入数据
     * */
    public static void insertDataOne(String dataBaseName, String collectionName, Document document) {
        MongoCollection<Document> collection = getCollection(dataBaseName).getCollection(collectionName);
        InsertOneResult insertOneResult = collection.insertOne(document);
    }

    /**
     * 插入数据
     * */
    public static void insertDataMany(String dataBaseName, String collectionName, List<Document> documentList) {
        MongoCollection<Document> collection = getCollection(dataBaseName).getCollection(collectionName);
        InsertManyResult result = collection.insertMany(documentList);
        log.info("插入的集合数量{}",result.getInsertedIds().size());
    }
}
